<template>
  <div class="div-main" style="width: 100%; min-height: 86vh">
    <div>
      <el-page-header @back="goBack" content="管理员账户信息" style="margin-bottom: 10px;">
      </el-page-header>
      <el-divider></el-divider>
    </div>
    <div style="display: flex; flex-direction: column; align-items: flex-start; flex-wrap: nowrap; height: auto;">
      <div style="margin-bottom: 20px; margin-left: 60px;">
        <span class="label-span"><i class="el-icon-user"></i> 用户名：</span>
        <span class="text-span">{{ adminInfo.administratorAccount }}</span>
      </div>
      <div style="margin-bottom: 20px; margin-left: 60px;">
        <span class="label-span"><i class=" el-icon-house"></i> 所属铁路管理局: </span>
        <span class="text-span">{{ railway.railwayName }}({{ railway.railwayAbbreviation }})</span>
      </div>
      <div style="margin-bottom: 20px; margin-left: 60px;">
        <span class="label-span"><i class=" el-icon-discover"></i> 所属铁路管理局地址：</span>
        <span class="text-span">{{ railway.railwayAddress }}</span>
      </div>
      <el-row style="margin-left: 70px;">
        <el-button type="primary" @click="step1">更改密码</el-button>
        <el-button type="warning" @click="step2">更改用户名</el-button>
        <el-button type="danger" @click="step3">更改所属铁路管理局</el-button>
      </el-row>
      <el-collapse-transition>
        <div v-if="div_show === 1" style="margin-left: 70px; margin-top: 20px;">
          <p style="font-weight: bold;">修改密码</p>
          <el-form style="width: auto; margin-top: 30px;" :model="updatePassword" :rules="rulesPassword"
            ref="updatePassword" label-width="82px">
            <el-form-item label="密码:" class="regist-item" prop="administratorPassword">
              <el-input type="password" show-password v-model="updatePassword.administratorPassword" autocomplete="off"
                style="width: 200px;"></el-input>
            </el-form-item>

            <el-form-item label="确认密码:" class="regist-item" prop="checkPassword">
              <el-input type="password" show-password v-model="updatePassword.checkPassword" autocomplete="off"
                style="width: 200px;"></el-input>
            </el-form-item>
          </el-form>
          <div style="display: flex; flex-wrap: nowrap; justify-content: center; margin-left: 20px;">
            <el-button type="primary" size="mini" plain :loading="passwordLoading" @click="setUpdatePassword">{{
              passwordLoading ? '修改中...'
              : '确认' }}</el-button>
            <el-button type="info" size="mini" plain @click="cancelChange('updatePassword')">取消</el-button>
          </div>

        </div>
        <div v-if="div_show === 2" style="margin-left: 70px; margin-top: 20px;">
          <p style="font-weight: bold;">修改用户名</p>
          <el-form style="width: auto; margin-top: 30px;" :model="updateAccount" :rules="rulesAccount" ref="updateAccount"
            label-width="82px">
            <el-form-item label="用户名:" class="regist-item" prop="updateAccount">
              <el-input v-model="updateAccount.updateAccount" autocomplete="off" style="width: 200px;"></el-input>
            </el-form-item>
          </el-form>
          <div style="display: flex; flex-wrap: nowrap; justify-content: center; margin-left: 20px;">
            <el-button type="primary" size="mini" plain :loading="accountLoading" @click="setUpdateAccount">{{
              accountLoading ? '修改中...'
              : '确认' }}</el-button>
            <el-button type="info" size="mini" plain @click="cancelChange('updateAccount')">取消</el-button>
          </div>

        </div>
        <div v-if="div_show === 3" style="margin-left: 70px; margin-top: 20px;">
          <p style="font-weight: bold;">修改所属铁路管理局</p>
          <el-form style="width: auto; margin-top: 30px;" :model="updateAuthority" ref="updateAuthority"
            label-width="88px">
            <el-form-item label="所属铁路局:" class="regist-item">
              <el-select placeholder="请选择所属铁路局" style="width: 200px;margin-right: 20px;" collapse-tags
                v-model="updateAuthority.updateAuthority">
                <el-option v-for="item in options" :key="item.id" :label="item.railwayName" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <div style="display: flex; flex-wrap: nowrap; justify-content: center; margin-left: 20px;">
            <el-button type="primary" size="mini" plain :loading="authorityLoading" @click="setUpdateAuthority">{{
              authorityLoading ? '修改中...'
              : '确认' }}</el-button>
            <el-button type="info" size="mini" plain @click="cancelAuthority()">取消</el-button>
          </div>

        </div>
      </el-collapse-transition>
    </div>
  </div>
</template>

<script>
import { toast } from '../../../composables/util'
export default {
  name: "adminInfo",
  data() {
    var validatePass = (rule, value, callback) => {
      if (value !== this.updatePassword.administratorPassword) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      adminInfo: {},
      railway: {},
      div_show: 0,
      // 更改密码
      passwordLoading: false,
      updatePassword: {
        administratorPassword: '',
        checkPassword: ''
      },
      rulesPassword: {
        administratorPassword: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 8, max: 16, message: '密码应为8-15位', trigger: ['blur', 'change'] }
        ],
        checkPassword: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          { validator: validatePass, trigger: ['blur', 'change'] }
        ],
      },
      // 修改用户名
      accountLoading: false,
      updateAccount: {
        updateAccount: '',
      },
      rulesAccount: {
        updateAccount: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
      },
      // 修改所属铁路局
      authorityLoading: false,
      options: [],
      updateAuthority: {
        updateAuthority: '',
      },
    }
  },
  methods: {

    goBack() {
      this.$router.push({ name: "adminHome" })
    },
    getAuthority() {
      this.request.get("/authority/getAuthority/" + this.adminInfo.railwayAuthority).then(
        response => {
          if (response.data.code === 1) {
            this.railway = response.data.data
            console.log(this.railway);
          }
        },
        error => {
          console.log(error);
        }
      )
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    cancelChange(name) {
      this.div_show = 0
      this.resetForm(name)
    },
    // 更改密码
    step1() {
      this.div_show = 1
    },
    setUpdatePassword() {
      this.$refs['updatePassword'].validate((valid) => {
        if (valid) {
          this.passwordLoading = true
          setTimeout(() => {
            this.putPassword()
          }, 1000)
        } else {
          console.log('error submit!!');
          return false;
        }
      })
    },
    putPassword() {
      const admin = {
        id: this.adminInfo.id,
        administratorPassword: this.updatePassword.administratorPassword,
        railwayAuthority: this.railway.id
      }
      console.log(admin);
      this.request.put("/administrator/updateAdmin", admin).then(
        response => {
          if (response.data.code === 1) {
            toast("修改密码成功,请重新登录！", this)
            this.exitLogin()
          } else {
            toast("修改密码失败,请稍后重试", this, "error")
          }
        },
        error => {
          console.log(error.message)
        }
      ).finally(() => {
        this.passwordLoading = false
      })
    },
    exitLogin() {
      sessionStorage.clear()
      this.$router.push("/adminlogin")
    },
    // 更改账户名
    step2() {
      this.div_show = 2
      this.updateAccount.updateAccount = this.adminInfo.administratorAccount
    },
    setUpdateAccount() {
      this.$refs['updateAccount'].validate((valid) => {
        if (valid) {
          this.accountLoading = true
          setTimeout(() => {
            this.putAccount()
          }, 1000)
        } else {
          console.log('error submit!!');
          return false;
        }
      })
    },
    putAccount() {
      const admin = {
        id: this.adminInfo.id,
        administratorAccount: this.updateAccount.updateAccount,
        railwayAuthority: this.railway.id
      }
      console.log(admin);
      this.request.put("/administrator/updateAdmin", admin).then(
        response => {
          if (response.data.code === 1) {
            this.$message({
              message: "修改账户名成功！",
              type: 'success'
            });
            sessionStorage.setItem('admin_info', JSON.stringify(admin))
            this.adminInfo = JSON.parse(sessionStorage.getItem('admin_info'))
            this.cancelChange('updateAccount')
            // this.$router.go(0)
          } else {
            this.$message({
              message: "修改账户名失败！",
              type: 'error'
            });
          }
        },
        error => {
          console.log(error.message)
        }
      ).finally(() => {
        this.accountLoading = false
      })
    },
    // 更改所属铁路局
    step3() {
      this.div_show = 3
      this.getAllAuthority()
      this.updateAuthority.updateAuthority = this.adminInfo.railwayAuthority
    },
    getAllAuthority() {
      this.request.get("/authority/getAllAuthority").then(
        response => {
          if (response.data.code === 1) {
            this.options = response.data.data
            console.log(this.options);
          }
        },
        error => {
          console.log(error);
        }
      )

    },
    setUpdateAuthority() {
      this.authorityLoading = true
      setTimeout(() => {
        this.putAuthority()
      }, 1000)
    },
    putAuthority() {
      const admin = {
        id: this.adminInfo.id,
        administratorAccount: this.adminInfo.administratorAccount,
        railwayAuthority: this.updateAuthority.updateAuthority
      }
      console.log(admin);
      this.request.put("/administrator/updateAdmin", admin).then(
        response => {
          if (response.data.code === 1) {
            this.$message({
              message: "修改账户名成功！",
              type: 'success'
            });
            sessionStorage.setItem('admin_info', JSON.stringify(admin))
            this.adminInfo = JSON.parse(sessionStorage.getItem('admin_info'))
            this.getAuthority()
            this.cancelAuthority()
            // this.$router.go(0)
          } else {
            this.$message({
              message: "修改账户名失败！",
              type: 'error'
            });
          }
        },
        error => {
          console.log(error.message)
        }
      ).finally(() => {
        this.authorityLoading = false
      })
    },
    cancelAuthority() {
      this.div_show = 0
      this.updateAuthority.updateAuthority = ''
    }
  },
  created() {
    this.adminInfo = JSON.parse(sessionStorage.getItem('admin_info'))
    this.getAuthority()
  },
  computed: {
  }
}

</script>

<style scoped>
.div-main {
  width: 100%;
  min-height: 86vh
}

.label-span {
  margin-left: 10px;
  font-size: medium;
  color: #93c5fd;
}

.text-span {
  font-weight: bold;
}
</style>